package com.taotao.tools.springmvc.csrf;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

/**
 * 防止CSRF攻击的启动类,使用@Import来引入或spring.factories来引入
 */
public class CsrfConfig implements WebMvcConfigurer {
    @Value("${csrf.patterns:}")
    private List<String> patterns = new ArrayList<>();

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MethodIdempotentCheck(new RedisTokenStore(stringRedisTemplate))).addPathPatterns(patterns);
    }

    @Bean
    public RedisTokenStore redisTokenStore() {
        return new RedisTokenStore(stringRedisTemplate);
    }

}